//
//  ZZLuckyTurntableView.m
//  LuckyTurntable
//
//  Created by 周英培 on 16/7/24.
//  Copyright © 2016年 周英培. All rights reserved.
//

#import "ZZLuckyTurntableView.h"
#import "ZZLuckyButton.h"
@interface ZZLuckyTurntableView ()

@property (nonatomic,weak) IBOutlet UIImageView *luckyRotateWheel;

@property (nonatomic,strong) CADisplayLink *link;

@property (nonatomic,weak) ZZLuckyButton *selectBtn;

@end

@implementation ZZLuckyTurntableView

// 在内部加载xib文件
+ (instancetype)luckyTurntableView {

    return [[[NSBundle mainBundle] loadNibNamed:@"ZZLuckyTurntableView" owner:nil options:nil] lastObject];
    
}

#pragma mark - 转盘转动
- (void)startRotote {

    CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(rotote)];
    
    [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    
    _link = link;
    
}

#pragma mark - 实现定时器的方法
- (void)rotote {
    
    self.luckyRotateWheel.transform = CGAffineTransformRotate(self.luckyRotateWheel.transform, M_PI_4 * 0.01);
}

#pragma mark - 开始选号
- (IBAction)chooseNumber {
    
    self.userInteractionEnabled = NO;

    [self.link invalidate];
    
    self.link = nil;
    
    //MARK:开启核心动画，让转盘快速转动起来
    // 1.创建核心动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    
    // 2.设置属性
    animation.duration = 3;
    
    // 以狮子为参考对象，三秒旋转五圈之后，狮子还在正上方
    CGFloat angle = self.selectBtn.tag *(M_PI * 2) / 12;
    
    animation.toValue = @(M_PI * 2 * 5 - angle);
    
    // 动画效果 加速的感觉
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    
    animation.delegate = self;
    
    // 3.添加到layer上
    [self.luckyRotateWheel.layer addAnimation:animation forKey:nil];
    
}

#pragma mark - 核心动画停止后，让控件的真身恢复过来
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {

    CGFloat angle = self.selectBtn.tag *(M_PI * 2) / 12;
    
    self.luckyRotateWheel.transform = CGAffineTransformMakeRotation(-angle);
    
   //MARK:核心动画停止后，通过代理给控制器弹出按选号框
    // 让代理执行协议方法
    if ([self.delegate respondsToSelector:@selector(luckyTurntableView:chooseNumber:)]) {
        
        [self.delegate luckyTurntableView:self chooseNumber:@"666666"];
        
    }
}

#pragma mark - 添加按钮
- (void)awakeFromNib {
    
    for (NSInteger i = 0; i < 12; i ++) {
        
        ZZLuckyButton *btn = [ZZLuckyButton buttonWithType:UIButtonTypeCustom];
        
        btn.tag = i;
        
        // 设置测试随机色
//        btn.backgroundColor = [UIColor colorWithRed:arc4random_uniform(256)/255.0 green:arc4random_uniform(256)/255.0 blue:arc4random_uniform(256)/255.0 alpha:1.0];
        
        [btn setBackgroundImage:[UIImage imageNamed:@"LuckyRototeSelected"] forState:UIControlStateSelected];
        
        //MARK:给按钮设置星座图片
        UIImage *normalImg = [self creatImageWithImageName:@"LuckyAstrology" andWithIndex:i];
        
        UIImage *selImg = [self creatImageWithImageName:@"LuckyAstrologyPressed" andWithIndex:i];
        
        [btn setImage:normalImg forState:UIControlStateNormal];
        
        [btn setImage:selImg forState:UIControlStateSelected];
        
        [self.luckyRotateWheel addSubview:btn];
        
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
}

#pragma mark - 按钮的点击事件
- (void)btnClick:(ZZLuckyButton *)sender {

    self.selectBtn.selected = NO;
    
    sender.selected = YES;
    
    self.selectBtn = sender;
    
}

#pragma mark - 根据图片的名称和索引来裁剪图片
- (UIImage *)creatImageWithImageName:(NSString *)imgName andWithIndex:(NSInteger)idx {

    UIImage *image = [UIImage imageNamed:imgName];
    
    // 设置图片裁剪区域
    CGFloat width = image.size.width / 12;
    CGFloat height = image.size.height;
    CGFloat x = width * idx;
    CGFloat y = 0;
    
    // 屏幕缩放比
    CGFloat scale = [UIScreen mainScreen].scale;
    
    // 将点坐标转化为像素点
    width *= scale;
    height *= scale;
    x *= scale;
    y *= scale;
    
    CGRect rect = CGRectMake(x, y, width, height);
    
    CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
    
    UIImage *clipImage = [UIImage imageWithCGImage:imageRef];
    
    return clipImage;
    
}

#pragma mark - 布局按钮
- (void)layoutSubviews {
    
    [super layoutSubviews];
    
    [self.luckyRotateWheel.subviews enumerateObjectsUsingBlock:^(__kindof ZZLuckyButton * _Nonnull btn, NSUInteger idx, BOOL * _Nonnull stop) {
        
        btn.bounds = CGRectMake(0, 0, 66, 143);
        
        btn.center = CGPointMake(self.luckyRotateWheel.bounds.size.width *0.5, self.luckyRotateWheel.bounds.size.height *0.5);
        
        // 设置铆点
        btn.layer.anchorPoint = CGPointMake(0.5, 1);
        
        // 设置按钮散开
        CGFloat angle = M_PI * 2 / 12;
        
        btn.transform = CGAffineTransformRotate(btn.transform, angle *idx);
        
    }];
    
}

@end
